/**
 * $(document).ready(); // Get user using ajax request
 * 
 * Add all functionality of chat in word
 * 
 * 1. startWebSocket 2. closeWebSocket 3. sendMsg 4. sendMsgEnter
 */
var wordChat = {};

wordChat.wordChatWS = null;

wordChat.user = null;

function initUser(user) {
	wordChat.user = user;
};

wordChat.getUser = function() {
	var contextPath = $("#contextPath").text();
	var ajaxRequest = contextPath + "/user.user";
	$.ajax({
		"url" : ajaxRequest,
		"cache" : false,
		"dataType" : "json",
		"error" : function(msg) {
			alert("Failed to connect to server");
		},
		"success" : function(data) {
			var user = data.user;
			initUser(user);
			startWebSocket($("#contextPath").text());
		}
	});
};

$(document).ready(function() {
	wordChat.getUser();
});

function startWebSocket(serverName) {
	if ('WebSocket' in window) {
		wordChatWS = new WebSocket("ws://" + window.location.host
				+ "/chat.chat");
	} else if ('MozWebSocket' in window)
		wordChatWS = new MozWebSocket("ws://" + window.location.host
				+ "/chat.chat");
	else
		alert("Your browser does not support Web Meeting System!");

	wordChatWS.onmessage = function(evt) {
		var chatWindow = $("#chatForm\\:chatMsg");
		var msg = evt.data.split("|");
		var date = new Date();
		var nowYear = date.getFullYear();
		var nowMonth = date.getMonth() > 10 ? date.getMonth() : "0"
				+ date.getMonth();
		var nowDate = date.getDate() > 10 ? date.getDate() : "0"
				+ date.getDate();
		var nowHour = date.getHours() > 10 ? date.getHours() : "0"
				+ date.getHours();
		var nowMinute = date.getMinutes() > 10 ? date.getMinutes() : "0"
				+ date.getMinutes();
		var nowSecond = date.getSeconds() > 10 ? date.getSeconds() : "0"
				+ date.getSeconds();
		var msgToShow = msg[0] + " " + nowYear + "-" + nowMonth + "-" + nowDate
				+ " " + nowHour + ":" + nowMinute + ":" + nowSecond + "\n"
				+ msg[1];
		if (null != chatWindow.val() && "" != chatWindow.val()) {
			chatWindow.val(chatWindow.val() + "\n" + msgToShow);
		} else {
			chatWindow.val(msgToShow);
		}
		chatWindow.scrollTop(chatWindow[0].scrollHeight - chatWindow.height());
	};
};

function closeWebSocket() {
	wordChatWS.close();
};

wordChat.sendMsg = function(data) {
	if ("success" == data.status) {
		var chatArea = $("#chatForm\\:chatArea");
		wordChatWS.send(chatArea.val());
		chatArea.val("");
		chatArea.innerHeight(60);
	}
};

wordChat.sendMsgEnter = function(event) {
	var e = event || window.event;
	if (e.ctrlKey && 13 === e.keyCode) {
		var chatArea = $("#chatForm\\:chatArea");
		wordChatWS.send(chatArea.val());
		chatArea.val("");
		chatArea.innerHeight(60);
		;
	}
};